<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2023 yoncron All rights reserved.
// +----------------------------------------------------------------------
// | Author: yoncron <yoncron@163.com>
// +----------------------------------------------------------------------

use Doctrine\Common\Annotations\AnnotationReader;
use Webman\Route;

//关闭默认路由
Route::disableDefaultRoute();

$dir_iterator = new \RecursiveDirectoryIterator(app_path());
$iterator = new \RecursiveIteratorIterator($dir_iterator);
foreach ($iterator as $file) {
    // 忽略目录和非php文件
    if (is_dir($file) || $file->getExtension() != 'php') {
        continue;
    }
    $file_path = str_replace('\\', '/',$file->getPathname());
    // 文件路径里不带controller的文件忽略
    if (strpos($file_path, 'controller') === false) {
        continue;
    }
    // 根据文件路径是被类名
    $class_name = str_replace('/', '\\',substr(substr($file_path, strlen(base_path())), 0, -4));
    if (!class_exists($class_name)) {
        echo "Class $class_name not found, skip route for it\n";
        continue;
    }
    $class = new ReflectionClass($class_name);
    $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
    $route = function ($class,$action) {
        $method = new ReflectionMethod($class,$action);
        $reader = new AnnotationReader();
        $route_annotation = $reader->getMethodAnnotation($method,\app\service\Route::class);
        if ($route_annotation && strlen($route_annotation->reqUrl) > 0) {
            Route::any($route_annotation->reqUrl, [$class,$action]);
        }
    };
    // 设置路由
    foreach ($methods as $item) {
        $action = $item->name;
        if (in_array($action, ['__construct', '__destruct','beforeAction','afterAction'])) {
            continue;
        }
        $route($class->getName(),$action);
    }


}